﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TMaterialRepository : BaseRepository<TMaterial>, ITMaterialRepository
    {
        public TMaterialRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加物料
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddMaterial(TMaterial m)
        {
            try
            {
                var obj = Context.TMaterials.AsNoTracking().FirstOrDefault(x => x.Code == m.Code);
                if (obj != null)
                {
                    return false;
                }
                m.CreateUserId = m.NowUserId;
                m.CreateUserName = m.NowUserRealName;
                m.ModifyUserId = m.NowUserId;
                m.ModifyUserName = m.NowUserRealName;
                m.CreateDate = DateTime.Now;
                m.ModifyDate = DateTime.Now;
                m.TypeId = 2;
                m.TypeName = "成品";
                m.TypeCode = "EndProduct";
                Context.TMaterials.Add(m);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除物料
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelMaterial(int mid)
        {
            var mobj = Context.TMaterials.Find(mid);

            if (mobj != null)
            {
                Context.TMaterials.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 根据主键获取对象信息
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TMaterial GetMaterialById(int mid)
        {
            return Context.TMaterials.Find(mid);
        }

        /// <summary>
        /// 生成一个物料号
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetMaterialCode(int mid)
        {
            string mcode = "";
            //查找该分类是否存在
            var obj = Context.TMaterialCategories.Find(mid);
            string mvalue = "";
            if (obj != null)
            {
                mcode += obj.Code + ",";
                //mvalue = obj.Id.ToString();
                int? j = obj.ParentId;
                //无限循环查找该对象是否为父级
                for (int i = 0; ; i++)
                {
                    //不是父级进行查询否则退出循环
                    if (obj.ParentId != 0)
                    {
                        //查找该对象
                        var objs = Context.TMaterialCategories.FirstOrDefault(x => x.Id == j);
                        if (objs != null)
                        {
                            //如果存在拿出编码
                            mcode += objs.Code + ",";
                            j = objs.ParentId;
                        }
                        else
                            break;
                    }
                    else
                        break;
                }

                string result = "";
                for (int i = 1; ; i++)
                {
                    if (i < 10)
                    {
                        result = mvalue + "0000" + i;
                    }
                    else if (i < 100)
                    {
                        result = mvalue + "000" + i;
                    }
                    else if (i < 1000)
                    {
                        result = mvalue + "00" + i;
                    }
                    else if (i < 10000)
                    {
                        result = mvalue + "0" + i;
                    }
                    else
                    {
                        result = i.ToString();
                    }
                    string inputStr = mvalue + "," + mcode + "CQXF";
                    string[] elements = inputStr.Split(",");
                    Array.Reverse(elements);
                    result = string.Join("", elements);
                    var mobj = Context.TMaterials.FirstOrDefault(x => x.Code == result);
                    if (mobj != null)
                    {
                        continue;
                    }
                    else
                        break;
                }

                return result;
            }
            return null;
        }

        /// <summary>
        /// 物料列表显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="materialcategoryid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetMaterialList(string mname, int materialcategoryid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TMaterials.AsNoTracking().AsQueryable();

            if (!string.IsNullOrEmpty(mname))
            {
                list = list.Where(x => x.Name.Contains(mname));
            }

            if (materialcategoryid != 0)
            {
                list = list.Where(x => x.MaterialCategoryId == materialcategoryid);
            }

            totalCount = list.Count();

            return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 修改物料
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdMaterial(TMaterial m)
        {
            var list = Context.TMaterials.AsNoTracking().FirstOrDefault(x => x.Id != m.Id && x.Code == m.Code);

            if (list != null)
            {
                return false;
            }

            m.ModifyUserId = m.NowUserId;
            m.ModifyUserName = m.NowUserRealName;
            m.ModifyDate = DateTime.Now;
            Context.TMaterials.Update(m);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 导出物料管理
        /// </summary>
        /// <returns></returns>
        public List<TMaterial> GetTMaterialExcel()
        {
            try
            {
                return Context.TMaterials.AsQueryable().ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取全部物料
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetAllMaterialList()
        {
            try
            {
                return Context.TMaterial.AsQueryable().ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 批量添加物料
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddMaterialList(List<TMaterial> list)
        {
            if(list.Count<=0)
            {
                return false;
            }
            Context.TMaterial.AddRange(list);
            return  Context.SaveChanges()>0;
        }
    }
}